package com.rickpan.aspect;

import com.rickpan.annotation.VipFeature;
import com.rickpan.exception.BusinessException;
import com.rickpan.service.VipFeatureService;
import com.rickpan.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * VIP功能权限切面
 */
@Aspect
@Component
@RequiredArgsConstructor
@Slf4j
public class VipFeatureAspect {

    private final VipFeatureService vipFeatureService;

    /**
     * 拦截VIP功能注解标记的方法
     */
    @Around("@annotation(vipFeature)")
    public Object checkVipFeature(ProceedingJoinPoint joinPoint, VipFeature vipFeature) throws Throwable {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            String featureCode = vipFeature.value();
            
            // 检查用户是否可以使用此功能
            boolean canUse = vipFeatureService.canUseFeature(userId, featureCode);
            
            if (!canUse) {
                String description = vipFeature.description().isEmpty() ? 
                    "功能" + featureCode : vipFeature.description();
                throw new BusinessException("您已达到" + description + "的使用限制，请升级VIP会员以获得更多权限");
            }

            // 执行原方法
            Object result = joinPoint.proceed();

            // 记录使用量
            if (vipFeature.recordUsage()) {
                vipFeatureService.recordFeatureUsage(userId, featureCode, vipFeature.usageCount(), null);
                log.debug("记录用户 {} 功能 {} 使用量: {}", userId, featureCode, vipFeature.usageCount());
            }

            return result;

        } catch (BusinessException e) {
            // 业务异常直接抛出
            throw e;
        } catch (Exception e) {
            log.error("VIP功能权限检查失败", e);
            throw new BusinessException("功能权限检查失败，请稍后重试");
        }
    }
}